/**   
 * @Title: ShiyixuanwuChooseActGroup.java 
 * @Package com.esun.rabbit2.viewer.mainact.lotteryhallact.shiyixuanwu 
 * @Description: 十一选五选号Activity
 * @Author: Miko baoz@500wan.com   
 * @Date: 2011-6-25 下午05:18:43  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.lotteryhallact.shiyixuanwu;

import java.util.Hashtable;

import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.shiyixuanwu.ShiyixuanwuLossDataCommunicater;
import com.esun.rabbit2.communicaters.shiyixuanwu.TermInfoCommunicater;
import com.esun.rabbit2.viewer.RegistAct;
import com.esun.rabbit2.viewer.mainact.OptionAct;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.shiyixuanwu.rabbittrunk.ShiyixuanwuBuyingInfo;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.shiyixuanwu.rabbittrunk.ShiyixuanwuContainer;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.shiyixuanwu.rabbittrunk.ShiyixuanwuLossData;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.RechargeMenuPage;
import com.esun.ui.R;
import com.esun.util.Vibrate;
import com.esun.util.log.EDebug;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * @ClassName: ShiyixuanwuChoosePageAct
 * @Description: 十一选五选号Activity
 * @Author: Miko baoz@500wan.com
 * @Date: 2011-6-25 下午05:48:59
 * 
 */
@SuppressWarnings("deprecation")
public class ShiyixuanwuChoosePageAct extends Activity implements OnClickListener, SensorListener {

	/************************* 晃动相关 **********************/
	private SensorManager sensorMgr;
	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 800;
	/*******************************************************/

	private View viewShiyixuanwuChoose; // 整个11选5的view
	private View viewShiyixuanwuChooOK; // 选号了界面

	private ShiyixuanwuChooseOkPage chooseOK; // 选好了页面
	private ShiyixuanwuContainer container; // 选号页面

	public static Handler handler;

	private TermInfoCommunicater communicater = new TermInfoCommunicater();

	private Hashtable<String, String> htTermInfo = new Hashtable<String, String>();

	// 选号界面是否显示
	private boolean isShowing = true;

	public static boolean isBuyPageShowing = false;

	private MyTimeLeftTimeCount ticker;

	private Dialog dialogTermExpired;

	public static boolean isCanBuy = false;

	private boolean isChoosePageShowing = true;

	private String strChangeBefore;
	public static final int DO_REFRESH = 10009;

	// 去往哪页 0选号界面 1选好了界面 购彩大厅
	public static int pageFlag = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init();

		// 是否存有未购买单
		if (ShiyixuanwuChooseOkList.getChooseList().getSize() > 0) {
			pageFlag = 1;
		} else {
			pageFlag = 0;
		}

		initHandler();
		getTermInfoInThread();
		getLossDataInThread();
	}

	private void initShake() {
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
		boolean accelSupported = sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME);

		if (!accelSupported) {
			// on accelerometer on this device
			sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
		}
	}

	private void init() {

		viewShiyixuanwuChoose = this.getLayoutInflater().inflate(R.layout.shiyixuanwu_choose, null);
		viewShiyixuanwuChooOK = this.getLayoutInflater().inflate(R.layout.shiyixuanwu_choose_pre_submit, null);

		if (chooseOK == null) {
			chooseOK = new ShiyixuanwuChooseOkPage(this, viewShiyixuanwuChooOK);
		}

		if (container == null) {
			container = new ShiyixuanwuContainer(viewShiyixuanwuChoose, this);
		}

		// 由于相互调用，所以将对象相互传入
		chooseOK.setContainer(container);
		container.setChoosePage(chooseOK);

	}

	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {

				case TempData.GET_TERM_INFO_SUCCESS:

					isCanBuy = true;

					resetTicker();
					ShiyixuanwuChooseOkPage.currentTerm = htTermInfo.get(TempData.EXPECT);
					container.updateTerm(htTermInfo.get(TempData.EXPECT), true);

					noticUserTermExpired();

					break;

				case TempData.GET_TERM_INFO_FAILED:

					isCanBuy = false;

					break;

				case TempData.GET_LOSS_DATA_SUCCESS:

					ShiyixuanwuContainer.shiyixuanwuChooseBallSpace.updateLossData(ShiyixuanwuLossData.getLossData().getSpace1(), ShiyixuanwuLossData.getLossData().getSpace2(), ShiyixuanwuLossData
							.getLossData().getSpace3(), ShiyixuanwuLossData.getLossData().getFree());

					break;

				case TempData.GET_LOSS_DATA_FAILED:
					break;

				case DO_REFRESH:
					if (ShiyixuanwuChooseOkList.getChooseList().getSize() == 0) {
						setContentView(container.getView());
					}else {
						setContentView(chooseOK.getView());
					}
						
					break;

				default:
					break;

				}
			}
		};
	}

	private void resetTicker() {
		if (ticker != null) {
			ticker.cancel();
		}

		ticker = new MyTimeLeftTimeCount(Long.parseLong(htTermInfo.get(TempData.LEFT_TIME)) * 1000, 1000);
		ticker.start();
	}

	private void noticUserTermExpired() {
		if (strChangeBefore != null) {
			if (isChoosePageShowing && ShiyixuanwuChooseOkList.getChooseList().getSize() > 0) {
				popTermExpiredAlert(strChangeBefore, htTermInfo.get(TempData.EXPECT));
			}

			if (isBuyPageShowing) {
				ShiyixuanwuChooseOkPage.popTermExpiredAlert(strChangeBefore, htTermInfo.get(TempData.EXPECT));
			}
		}
		strChangeBefore = htTermInfo.get(TempData.EXPECT);
	}

	private void popTermExpiredAlert(String before, String after) {

		if (dialogTermExpired == null) {
			dialogTermExpired = new Dialog(this, R.style.dialog);
			View alertView = getLayoutInflater().inflate(R.layout.shiyixuanwu_alert_term_expired, null);

			Button btnClear = (Button) alertView.findViewById(R.id.shiyixuanwu_alert_term_expired_btn_clear);
			Button btnCancel = (Button) alertView.findViewById(R.id.shiyixuanwu_alert_term_expired_btn_cancel);

			TextView tvMSG = (TextView) alertView.findViewById(R.id.shiyixuanwu_alert_term_expired_content);
			tvMSG.setText("第" + before + "期已结束，现在购买为第" + after + "期，确定继续购买吗？");

			View.OnClickListener listener = new OnClickListener() {

				@Override
				public void onClick(View v) {

					dialogTermExpired.dismiss();

					switch (v.getId()) {

					case R.id.shiyixuanwu_alert_term_expired_btn_clear:

						ShiyixuanwuChooseOkList.getChooseList().reset();
						chooseOK.refresh();
						container.setNoBtnCancel();

						break;

					case R.id.shiyixuanwu_alert_term_expired_btn_cancel:
						break;

					default:
						break;
					}
				}
			};

			btnClear.setOnClickListener(listener);
			btnCancel.setOnClickListener(listener);

			dialogTermExpired.setContentView(alertView);
			dialogTermExpired.show();
		} else {
			dialogTermExpired.show();
		}

	}

	private class MyTimeLeftTimeCount extends CountDownTimer {

		String strMin;
		String strSec;
		String strHour;
		long time;

		public MyTimeLeftTimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {

			time = millisUntilFinished / 1000;

			// 剩余小时
			strHour = String.valueOf(time / 3600);
			if (strHour.length() < 2) {
				strHour = TempData.NUM0 + strHour;
			}

			time = time % 3600;

			// 剩余分钟数
			strMin = String.valueOf(time / 60);
			if (strMin.length() < 2) {
				strMin = TempData.NUM0 + strMin;
			}

			// 剩余秒数
			strSec = String.valueOf(time % 60);
			if (strSec.length() < 2) {
				strSec = TempData.NUM0 + strSec;
			}

			container.refreshTimeLeft(strHour + "小时" + strMin + "分" + strSec + "秒");
		}

		@Override
		public void onFinish() {

			container.updateTerm("期号信息获取中...", false);
			container.refreshTimeLeft(TempData.NULL_MARK);
			getTermInfoInThread();
		}
	}

	private void getLossDataInThread() {

		EDebug.o(ShiyixuanwuActGroup.class, "开始获漏号");

		new Thread() {

			@Override
			public void run() {
				super.run();

				while (true && isShowing) {

					if (isGetLossDataSuccess()) {
						try {
							Thread.sleep(60000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} else {
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

				}

			}
		}.start();
	}

	private boolean isGetLossDataSuccess() {

		ShiyixuanwuLossDataCommunicater communicater = new ShiyixuanwuLossDataCommunicater();

		if (communicater.getServerInfo()) {
			communicater.getLossData();
			Message msg = handler.obtainMessage(TempData.GET_LOSS_DATA_SUCCESS);
			handler.sendMessage(msg);
			return true;
		} else {
			return false;
		}
	}

	private void getTermInfoInThread() {

		EDebug.o(ShiyixuanwuActGroup.class, "开始获取期号");
		isCanBuy = false;

		new Thread() {

			@Override
			public void run() {
				super.run();

				while (true && isShowing) {
					if (doGetTermInfo()) {
						break;
					} else {
						EDebug.o(ShiyixuanwuActGroup.class, "【获取十一选五期号失败】  3秒后重试");
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {

						}
					}
				}
			}
		}.start();
	}

	private boolean doGetTermInfo() {

		if (communicater.getTermInfo()) {

			htTermInfo = communicater.getAvilableTerm();

			Message msg = handler.obtainMessage(TempData.GET_TERM_INFO_SUCCESS);
			handler.sendMessage(msg);

			return true;
		} else {

			Message msg = handler.obtainMessage(TempData.GET_TERM_INFO_FAILED);
			handler.sendMessage(msg);
			return false;
		}
	}

	@Override
	public void onClick(View v) {

	}

	@Override
	protected void onResume() {
		initShake();
		super.onResume();
		isShowing = true;
		isChoosePageShowing = true;

		chooseOK.refresh();

		if (pageFlag == -1) {
			getParent().finish();
		} else if (pageFlag == 0) {
			setContentView(container.getView());
		} else if (pageFlag == 1) {
			setContentView(chooseOK.getView());
		}

		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());

		if (UserInfo.getUserInfo().isBuyingRecharge()) {
			getParent().finish();
			UserInfo.getUserInfo().setBuyingRecharge(false);
		}

		if (RegistAct.isRegistSucceed || OptionAct.isLoginSucceed) {
			if (Double.parseDouble(UserInfo.getUserInfo().getUserBalance()) - ShiyixuanwuBuyingInfo.getBuyingInfo().getMoney() < 0) {
				showZeroMoneyDialog();
			}
			RegistAct.isRegistSucceed = false;
			OptionAct.isLoginSucceed = false;
		}
	}

	@Override
	protected void onPause() {

		if (sensorMgr != null) {
			sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
			sensorMgr = null;
		}

		super.onPause();

		isChoosePageShowing = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isShowing = false;
	}

	@Override
	public void onAccuracyChanged(int sensor, int accuracy) {

	}

	@Override
	public void onSensorChanged(int sensor, float[] values) {

		if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
			long curTime = System.currentTimeMillis();
			if ((curTime - lastUpdate) > 100) {
				long diffTime = (curTime - lastUpdate);
				lastUpdate = curTime;

				x = values[SensorManager.DATA_X];
				y = values[SensorManager.DATA_Y];
				z = values[SensorManager.DATA_Z];

				float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

				if (speed > SHAKE_THRESHOLD) {
					if (pageFlag == 0) {
						container.doRandom();
						new Vibrate(this).playVibrate(-1);
					}
				}
				last_x = x;
				last_y = y;
				last_z = z;
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			getParent().finish();
			if (UserInfo.getUserInfo().isRebuy()) {
				UserInfo.getUserInfo().setRebuy(false);
				ShiyixuanwuChooseOkList.getChooseList().reset();
			}
		}
		return false;
	}

	@Override
	public boolean onTrackballEvent(MotionEvent event) {

		Activity parent = getParent();
		if (parent != null) {
			parent.onTrackballEvent(event);
			return true;
		}
		return false;
	}

	private void showZeroMoneyDialog() {
		final Dialog zeroMoneyDialog = new Dialog(ShiyixuanwuChoosePageAct.this, R.style.dialog);
		zeroMoneyDialog.getWindow().setContentView(R.layout.viewerutil_dialog_zeromoney);
		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View v) {

				switch (v.getId()) {
				case R.id.viewerutildialogzeromoney_btn_cancel:
					zeroMoneyDialog.dismiss();
					break;

				case R.id.viewerutildialogzeromoney_btn_recharge:
					zeroMoneyDialog.dismiss();
					Intent intent = new Intent();
					intent.setClass((Activity) ShiyixuanwuChoosePageAct.this, RechargeMenuPage.class);
					ShiyixuanwuChoosePageAct.this.startActivity(intent);
					UserInfo.getUserInfo().setBuyingRecharge(true);
					break;
				default:
					break;
				}
			}
		};
		Button btnCancel = (Button) zeroMoneyDialog.getWindow().findViewById(R.id.viewerutildialogzeromoney_btn_cancel);
		btnCancel.setText("继续购彩");
		btnCancel.setOnClickListener(listener);
		Button btnRecharge = (Button) zeroMoneyDialog.getWindow().findViewById(R.id.viewerutildialogzeromoney_btn_recharge);
		btnRecharge.setOnClickListener(listener);
		((TextView) zeroMoneyDialog.getWindow().findViewById(R.id.viewerutildialogzeromoney_tv_userName)).setText("您的账户余额不足，您可以通过[我的彩票]-[充值]，可选择使用银联卡或神州卡充值。");
		((TextView) zeroMoneyDialog.getWindow().findViewById(R.id.viewerutildialogzeromoney_tv_tipWord)).setVisibility(View.INVISIBLE);
		zeroMoneyDialog.show();
	}
}
